package com.ghp.admin.controller;

import com.ghp.admin.service.FileInfoService;
import com.ghp.common.model.dto.file.FileChunkDTO;
import com.ghp.common.utils.response.ResponseResult;
import com.ghp.file.constants.enums.FileRequestTypeEnum;
import com.ghp.file.request.FileRequestFactory;
import com.ghp.request.annotation.RequestLimit;
import com.ghp.request.enums.RequestLimitStrategy;
import io.swagger.annotations.Api;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import static com.ghp.common.constants.ErrorMessageConstants.PARAMS_NOT_NULL;

/**
 * @author ghp
 * @title
 * @description
 */
@Api
@RestController
@RequestMapping("/file")
@Validated
public class FileController {

    @Resource
    private FileInfoService fileInfoService;

    /**
     * 上传预检（用于实现秒传、断点续传）
     */
    @GetMapping("/upload")
    public ResponseResult uploadFilePrecheck(@Valid FileChunkDTO fileChunkDTO) {
        return fileInfoService.uploadFilePrecheck(fileChunkDTO);
    }

    /**
     * 文件上传（分片上传）
     */
    @PostMapping("/upload")
    @RequestLimit(strategy = RequestLimitStrategy.TOKEN_BUCKET, qps = 10)
    public ResponseResult uploadFile(@Valid FileChunkDTO fileChunkDTO) {
        return fileInfoService.uploadFile(fileChunkDTO);
    }

    /**
     * 授权访问（OSS私有空间中的图片需要授权后才能访问）
     */
    @GetMapping("/authorization")
    public ResponseResult authorization(@NotBlank(message = PARAMS_NOT_NULL) String fileUrl) {
        return ResponseResult.success(FileRequestFactory.getInstance()
                .getFileRequest(FileRequestTypeEnum.TENCENTYUN)
                .authorizationFilURL(fileUrl));
    }

    /**
     * 文件下载（下载OSS上需要授权的文件）
     */
    @GetMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) {
        FileRequestFactory.getInstance()
                .getFileRequest(FileRequestTypeEnum.TENCENTYUN)
                .downloadByPost(response, fileUrl);
    }

}
